import axios from 'axios'
import getToken from '@/utils/storage'

const token = 'eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlkIjoiMSIsIm5hbWUiOiJhZG1pbiIsImV4dEluZm8iOiIiLCJleHAiOjE1NTAyMjE0NjR9.LFq22DjOMYWOomKXuXGaxpeaX6O2uprZQv5LDVd3H79jbRKf-hS0dlhieLxYMo2nJmLyTCQ1cAS-ieuOLWC9jWcEKeHfjaRAW1i7TOoOLulJvCGoFw7dPZlGKgtriLB2Uuhw-pOfLaTmm9pM8AugsCrB1goBkvLDiQtjp5ZrUMU'

// axios 配置
const CancelToken = axios.CancelToken;

axios.defaults.timeout = 50000;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; // 配置请求头
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'; // 配置请求头
// axios.defaults.baseURL = $core.use('http'); //确认协议和地址
axios.defaults.withCredentials = false; // axios 默认不发送cookie，需要全局设置true发送cookie

// 可根据开发环境和生产环境，设置axios网络请求的baseURL
// axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? 'xxxxx' : 'xxxx'; 

// 本地mock直接设置模拟网络地址baseURL
axios.defaults.baseURL = 'http://10.0.54.7/'; 

// 代理设置网络请求的baseURL为api，代理转发替换为''
// axios.defaults.baseURL = '/api'; 

console.log(process.env.NODE_ENV);

const headers = {
    // 'X-Token': token,
    'X-Token': getToken()
}
axios.interceptors.request.use((config) => {
    if (config.method === 'post') {
        //   config.data = qs.stringify(config.data);
    }
    Object.assign(config.headers, headers)

    // http请求config包含回调方法cancel，调用则取消http请求
    if (config && config.cancel) {
        config.cancelToken = new CancelToken(c => { //强行中断请求要用到的
            // Vue.prototype.$cancel = c;
            config.cancel(c)
        })
    }

    return config;
}, (error) => {
    return Promise.reject(error);
});

//返回状态判断
axios.interceptors.response.use((res) => {
    let result = res.data;
    if (res.status == 200) {
        result.success = true;
    } else {
        result.success = false;
    }
    return result;
}, (error) => {
    //404等问题可以在这里处理
    return Promise.reject(error);
});

export default {
    post: (path, data, config) => {
        return new Promise((resolve, reject) => {
            axios.post(path, data, config)
                .then(function (response) {
                    resolve(response);
                })
                .catch(function (error) {
                    reject(error);
                });
        });
    },
    get: (path, params, config) => {
        return new Promise((resolve, reject) => {
            axios.get(path, {
                    params
                }, config)
                .then(function (response) {
                    resolve(response);
                })
                .catch(function (error) {
                    reject(error);
                });
        });
    },
}